package com.infore.dataReceiving.netty.client;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import org.hibernate.boot.model.naming.ImplicitNameSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.infore.dataReceiving.util.Air212InstructionsHandleUtil;

import java.net.InetSocketAddress;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * <b>标题:  Netty 服务  </b><br />
 * <pre>
 * </pre>
 * @author zzh
 * @date 2019-4-18
 */
@Component
@Qualifier("nettyClient")
public class NettyClient {
	
	@Autowired
	@Qualifier("clientChannelInitializer")
	private ClientChannelInitializer clientChannelInitializer;
	
	private static ChannelFuture future;

    public void sendMessage(String host,int port,String instruction) throws Exception {
    	
    	String flag = Air212InstructionsHandleUtil.remoteMap.get("remoteFlag");
    	
    	if(future==null||"1".equals(flag)) {
    		getChannelFuture(host,port,instruction);
    	}
    	if(future!=null) {
    		try {
            	future.channel().writeAndFlush(instruction);
            	Air212InstructionsHandleUtil.remoteMap.put("remoteFlag", "0");
        	}catch (Exception e) {
        		future.channel().close();
        		future=null;
        		e.printStackTrace();
    		}
    	}
    }
    
    
    public ChannelFuture getChannelFuture(String host,int port,String instruction) throws Exception {
    	EventLoopGroup group = new NioEventLoopGroup();
    	try {
    		Bootstrap b = new Bootstrap();
            b.group(group)
	            .channel(NioSocketChannel.class)
	    		.option(ChannelOption.TCP_NODELAY, true)
	    		.option(ChannelOption.SO_KEEPALIVE, true)
	    		.handler(clientChannelInitializer);
        	future = b.connect(host, port).sync();
    	}catch (Exception e) {
    		future.channel().close();
    		future=null;
    		e.printStackTrace();
		}
    	return future;
    }
    
    
}
